'use strict';

module.exports = app => {
  return class utilsService extends app.Service {
    /**
     * 获取列表信息
     * @param {string} dataTable - 查询的表
     * @param {function} method - 查询条件
     * @return {number} - 查询的总条数
     */
    async getCount(dataTable, method) {
      const { app } = this;
      let count = 0;
      if (!method) {
        count = (await app.knex(dataTable)
        .count('* as count')
        .first())['count'];
      } else {
        count = (await app.knex(dataTable)
        .count('* as count')
        .first()
        .where(method))['count'];
      }
      return count;
    }
    /**
     * 获取列表信息
     * @param {string} dataTable - 查询的表
     * @param {number} page - 页码
     * @param {number} limit - 每页条数
     * @param {function} method - 查询条件
     * @param {object} sort - 排序条件
     * @return {object} - 查询信息
     */
    async getListDetail(dataTable, select, page, limit, sort, method) {
      const { app } = this;
      const offset = (page - 1) * limit;
      const { sortProp, sortOrder } = sort;
      let data = null;
      if (sortProp) {
        if (method) {
          data = await app.knex(dataTable)
          .select(select)
          .where(method)
          .limit(limit)
          .offset(offset)
          .orderBy(sortProp, sortOrder);
        } else {
          data = await app.knex(dataTable)
          .select(select)
          .limit(limit)
          .offset(offset)
          .orderBy(sortProp, sortOrder);
        }
      } else {
        if (method) {
          data = await app.knex(dataTable)
          .select(select)
          .where(method)
          .limit(limit)
          .offset(offset);
        } else {
          data = await app.knex(dataTable)
          .select(select)
          .limit(limit)
          .offset(offset);
        }
      }
      return data;
    }
  };
};
